package de.eventdroid.dao;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import de.eventdroid.R;
import de.eventdroid.helper_classes.TextHandler;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.net.ParseException;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class DatenbankLocation extends ListActivity {
	
	private JSONArray jSONArray;
	private String resultString = null;
	private StringBuilder stringBuilder =null;
	private InputStream inputStream = null;	
	private ArrayList<String> meineListe = new ArrayList<String>();
	private ArrayList<String> listItemsToID = new ArrayList<String>();
	private ListAdapter listenAdapter = null;
	private ArrayAdapter<String> locationArrAdapter = null;
	private ListView listView;
	private Intent showSpecLocData;
	private TextHandler myTexthandler;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {		
		super.onCreate(savedInstanceState);
//		setContentView(R.layout.datenbank_location);
		myTexthandler = new TextHandler();
	}
	
	/**
	 * This Method resolves the users request for new Locations
	 * 
	 * @param view actual View the user clicked on
	 */
	public void onButtonClick(View view) {		
		
//		listView = (ListView)findViewById(R.id.list);
//		showSpecLocData = new Intent(this, DatenbankSpecLocation.class);
//		
//		listView.setOnItemClickListener(new OnItemClickListener() {
//		
//			@Override
//			public void onItemClick(AdapterView<?> adapView, View view, int position,
//					long id) {
//				
//				Log.e("ICH UEBERGEBE ", meineListe.get(Integer.parseInt(listItemsToID.get(position))));
//				
//				listView.getItemAtPosition(position);						
//				showSpecLocData.putExtra("location_data", meineListe.get(Integer.parseInt(listItemsToID.get(position))));
//				startActivity(showSpecLocData);
//				
//			}
//		});
//		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//		meineListe.clear();
		
//		/* http-post - get Data from the RESTful Server */
//		try{
//		    HttpClient httpclient = new DefaultHttpClient();
//		    HttpPost httppost = new HttpPost("http://www.redphoenix.de/eventdroid/getAllLocations.php"); //212.72.182.14
//		    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//		    HttpResponse response = httpclient.execute(httppost);
//		    HttpEntity entity = response.getEntity();
//		    inputStream = entity.getContent(); 
//		} catch(Exception e) {
//		    Log.e("log_tag", "Error in http connection: "+e.toString());
//		}
		
		/* Convert response to string */
		try{
			BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,"utf8"),8);
		    stringBuilder = new StringBuilder();
		    stringBuilder.append(reader.readLine() + "\n");
		    String line="empty";
		    while ((line = reader.readLine()) != null) {
		    	stringBuilder.append(line + "\n");
		    }
		    inputStream.close();
		    resultString = stringBuilder.toString();
		} catch(Exception e) {
			Log.e("log_tag", "Error converting result "+e.toString());
		}
		
		try{
			
			jSONArray = new JSONArray(resultString);
		    int locationFound = 0;
		    
			/* Preparing the strings */
			JSONObject json_data = null;
			locationFound = jSONArray.length();
			
		    for(int i=0;i<locationFound;i++){
		    	
		    	stringBuilder = new StringBuilder();
		    	json_data = jSONArray.getJSONObject(i);
		    	
		    	stringBuilder.append(myTexthandler.replaceUmlauts(json_data.getString("location_name")+"\n","html"));
		    	stringBuilder.append(myTexthandler.replaceUmlauts(json_data.getString("location_description")+"\n","html"));
		    	stringBuilder.append(myTexthandler.replaceUmlauts(json_data.getString("location_adress")+"\n","html"));
		    	stringBuilder.append(myTexthandler.replaceUmlauts(json_data.getString("location_zip")+" - ","html"));
		    	stringBuilder.append(myTexthandler.replaceUmlauts(json_data.getString("location_town"), "html"));
		    	
		        /* Replace with List when build */
		        meineListe.add(stringBuilder.toString());
		        
		        /* ID reference for later reading */
		        try {
		        	listItemsToID.add(json_data.getString("location_id"));
		        } catch (NumberFormatException nfe) {
		        	Log.e("Number Format Exception","The Location ID which is parsed must be a integer value: "+ nfe.getMessage());
		        }
		        
		    }
		    
		    /* Allocate ListAdapter for filling the ListView */
		    locationArrAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, meineListe);
		    locationArrAdapter.notifyDataSetChanged();
		    listenAdapter = locationArrAdapter;
		    listView.setAdapter(listenAdapter);
		    
		    /* Number of found Locations in Toast */
		    Toast.makeText(getBaseContext(), "Es wurden "+locationFound+" Locations gefunden." ,Toast.LENGTH_LONG).show();
		    
		} catch(JSONException e1) {
			Log.e("log_tag", "JSON Exception: "+e1.toString());
		} catch (ParseException e1) {
			Log.e("log_tag", "Parsing Exception: "+e1.toString());
		}
		
	}
	
	/**
	 * This method fetches the GeoData of the selected Location
	 * 
	 * @param locationID Locations ID
	 * @return ArrayList with two strings which contain the two Geo-Coordinates
	 */
	private ArrayList<String> getLocationGeoData(int locationID) {
		
		return new ArrayList<String>();
		
	}

}
